"use strict";

//require
var fs = require('fs');
var walk = require('walk')
var path = require('path');
var UglifyJS = require("uglify-js");
var CleanCSS = require('clean-css');


/*
 * 适用于django1.4+的项目
 * django1.4+路径规则: 
 * static: appName/appName/static/
 * template: appName/appName/templates/
 * @param options.root  网站根目录
 * @param options.project  项目名
 */
module.exports = function(options){
    //网站根目录
    var workspace = options.root;
    //项目名称
    var projectName = options.project;
    //当前时间戳
    var timesitemap = parseInt((new Date().getTime() - new Date(2013,11,29,23,59,59).getTime())/(1000*60));
    //js path
    var jsPath = path.join(workspace, projectName, 'static/js');
    //css path
    var cssPath = path.join(workspace, projectName, 'static/css');


    //更新时间戳
    var updateStamap = function(file, callback){
    	var extname = path.extname(file);

    	if(extname == '.css' || extname == '.js' || extname == '.jinja'){
    		fs.readFile(file, function(e, data){
				var extname = path.extname(file);
				var content = data.toString('utf-8').replace(/\{timestamp\}/gi, timesitemap);
				
				if(e){throw e;}

				if(extname == '.css'){
					content = new CleanCSS().minify(content);
				}

				if(extname == '.js'){
					var miniData = UglifyJS.minify(content, {
						fromString: true,
						mangle: true
					});
					content = miniData.code;
				}

				fs.writeFile(file, content, function(err){
					callback && callback();
				});
			});
    	}
    };

    //压缩js
    var compressJs = function(){
		var walker = walk.walkSync(jsPath, {
			followLinks: false,
			filters: ['lib', 'plugins', 'edit']
		});
    	
    	walker.on('file', function(root, fileStats, next){
    		if(root.indexOf('/lib') == -1 && root.indexOf('/plugins') == -1 && root.indexOf('/edit') == -1){
    			console.log(fileStats.name);
                updateStamap(path.join(root, fileStats.name), function(){
    				next();
	    		});
    		}else{
    			next();
    		}
    	});

    	walker.on('error', function(root, fileStats, next){
    		console.log('js error');
    		next();
    	});

    	walker.on('end', function(root, fileStats, next){
    		console.log('compress js done');
    	});
    };

    //压缩css
    var compressCss = function(){
    	var walker = walk.walkSync(cssPath, {
			followLinks: false
		});

		walker.on('file', function(root, fileStats, next){
            console.log(fileStats.name);
			updateStamap(path.join(root, fileStats.name), function(){
				next();
    		});
    	});

    	walker.on('error', function(root, fileStats, next){
    		console.log('css error');
    		next();
    	});

    	walker.on('end', function(root, fileStats, next){
    		console.log('compress css done');
    		//压缩js
    		compressJs();

            //替换base.jinja时间戳
            updateStamap(path.join(workspace, projectName, 'templates/base.jinja'));
    	});
    }


    return {
    	compress: compressCss
    }
}